import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:syria_sports/core/app_export.dart';
import 'package:flutter/material.dart';
import 'package:syria_sports/core/utils/show_toast.dart';
import 'package:syria_sports/data/apiClient/apis_data.dart';
import 'package:syria_sports/data/models/auth/user.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:syria_sports/presentation/admin_home_tabs/players_tab/bloc/players_tab_cubit.dart';
import 'package:syria_sports/presentation/players/add_player_page/bloc/add_player_page_screen.dart';
import 'package:syria_sports/presentation/players/add_player_page/widgets/my_circle_avatar.dart';
import 'package:syria_sports/presentation/admin_home_tabs/cp_tab/bloc/cp_cubit.dart';
import '../../../../data/controllers/player_controller.dart';
import '../../../../dialogs/add_attendance_dialog.dart';
import '../../../../dialogs/delete_player_confirmation.dart';
import '../../../players/player_profile_screen/player_profile_screen.dart';
import 'package:fluent_ui/fluent_ui.dart' as fui;


class PlayerListItemView extends StatefulWidget {
  final User user;
  final int index;
  final PlayersTabCubit? playersTabCubit;
  final Function(bool ,User)? onSelected;

  const PlayerListItemView({super.key, required this.user, required this.index, this.playersTabCubit, this.onSelected});

  @override
  State<PlayerListItemView> createState() => _PlayerListItemViewState();
}

class _PlayerListItemViewState extends State<PlayerListItemView> {
  late bool selected;

  @override
  void initState() {
    selected = false;
    super.initState();
  }


  @override
  Widget build(BuildContext context) {
    final menuController = fui.FlyoutController();
    late LongPressDownDetails longPD ;
    return fui.FlyoutTarget(
        controller: menuController,
        child: GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => PlayerProfileScreen.builder(
                  index: widget.index,
                  context: context,
                  user: widget.user,
                ),
              ),
            );
          },
          onSecondaryTapDown: (details) {
            _showContextMenu(context, details.globalPosition);
          },
          onLongPressDown: (details){
            longPD = details;
          },
          onLongPress: (){
            _showContextMenu(context, longPD.globalPosition);
          },
          child:BlocBuilder<PlayersTabCubit,PlayersTabState>(
            buildWhen: (p,c) {
              if(c is SelectAllPlayersState) {
                selected =c.value;
              }
              return c is SelectAllPlayersState;
            },
            builder:(context,state) =>Slidable(
              enabled: PrefUtils.isCoach(),
              // The start action pane is the one at the left or the top side.
              startActionPane: ActionPane(
                // A motion is a widget used to control how the pane animates.
                motion: const ScrollMotion(),

                /*// A pane can dismiss the Slidable.
        dismissible: DismissiblePane(onDismissed: () {}),*/

                // All actions are defined in the children parameter.
                children: [
                  // A SlidableAction can have an icon and/or a label.
                  SlidableAction(
                    onPressed: (context){
                      showDeleteConfirmation(context, widget.user);
                    },
                    backgroundColor: Colors.transparent,
                    foregroundColor: Colors.red,
                    icon: Icons.delete,
                    label: 'حذف',
                  ),
                  SlidableAction(
                    onPressed: (context){
                      Navigator.push(context, MaterialPageRoute(builder: (context) => AddPlayerPageScreen(player:widget.user,playersTabCubit: widget.playersTabCubit,)));
                    },
                    backgroundColor: Colors.transparent,
                    foregroundColor: Colors.orange,
                    icon: Icons.edit,
                    label: 'تعديل',
                  ),
                ],
              ),
              endActionPane: ActionPane(
                motion: const ScrollMotion(),
                children: [
                  SlidableAction(
                    onPressed: (context){
                      showAddAttendanceDialog(context ,widget.user);
                    },
                    backgroundColor: Colors.transparent,
                    foregroundColor: Colors.orange,
                    icon: Icons.pending_actions_rounded,
                    label: 'إضافة حضور',
                  ),
                ],
              ),
              child: GestureDetector(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => PlayerProfileScreen.builder(
                        index: widget.index,
                        context: context,
                        user: widget.user,
                      ),
                    ),
                  );
                },
                child: Card(
                  color: Theme.of(context).colorScheme.secondary,
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Row(
                      children: [
                        Hero(
                          tag: "player_selected${widget.index}",
                          child: MyCircleAvatar(
                            borderColor: Colors.red,
                            backgroundColor:Theme.of(context).colorScheme.onPrimaryContainer,
                            editMode: false,
                            width: 38,
                            activeIconWidth: 22,
                            imageURL: widget.user.image,
                            active: widget.user.activeValue == '1',
                          ),
                        ),
                        const SizedBox(width: 8), // مسافة أفقية بين العناصر
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(widget.user.fullName, style: theme.textTheme.titleMedium),
                              Text("المستوى: ${widget.user.level}", style: CustomTextStyles.bodySmallOnPrimary),
                            ],
                          ),
                        ),
                        if(widget.playersTabCubit?.selectedMode == true)
                          Align(
                            alignment: Alignment.topLeft,
                            child: Checkbox(
                              value: selected,
                              onChanged: (value){
                                setState(() {
                                  selected = value??false;
                                  print(selected);
                                  //widget.playersTabCubit?.add(ChangeSelectMode(mod: true));
                                });
                                widget.onSelected?.call(value??false,widget.user);
                              },
                            ),
                          )else
                        CustomImageView(
                          imagePath: ImageConstant.imgArrowLeftBlueGray300,
                          height: 32.adaptSize,
                          width: 32.adaptSize,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ),
        )
    );
  }
  Widget build2(BuildContext context) {
    return Slidable(
      enabled: PrefUtils.isCoach(),
      // The start action pane is the one at the left or the top side.
      startActionPane: ActionPane(
        // A motion is a widget used to control how the pane animates.
        motion: const ScrollMotion(),

        /*// A pane can dismiss the Slidable.
        dismissible: DismissiblePane(onDismissed: () {}),*/

        // All actions are defined in the children parameter.
        children: [
          // A SlidableAction can have an icon and/or a label.
          SlidableAction(
            onPressed: (context){
              showDeleteConfirmation(context, widget.user);
            },
            backgroundColor: Colors.transparent,
            foregroundColor: Colors.red,
            icon: Icons.delete,
            label: 'حذف',
          ),
          SlidableAction(
            onPressed: (context){
               Navigator.push(context, MaterialPageRoute(builder: (context) => AddPlayerPageScreen(player:widget.user,playersTabCubit: widget.playersTabCubit,)));
            },
            backgroundColor: Colors.transparent,
            foregroundColor: Colors.orange,
            icon: Icons.edit,
            label: 'تعديل',
          ),
        ],
      ),
      endActionPane: ActionPane(
        motion: const ScrollMotion(),
        children: [
          SlidableAction(
            onPressed: (context){
              showAddAttendanceDialog(context ,widget.user);
            },
            backgroundColor: Colors.transparent,
            foregroundColor: Colors.orange,
            icon: Icons.pending_actions_rounded,
            label: 'إضافة حضور',
          ),
        ],
      ),
      child: GestureDetector(
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => PlayerProfileScreen.builder(
                index: widget.index,
                context: context,
                user: widget.user,
              ),
            ),
          );
        },
        child: Card(
          color: Theme.of(context).colorScheme.secondary,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              children: [
                Hero(
                  tag: "player_selected${widget.index}",
                  child: MyCircleAvatar(
                    borderColor: Colors.red,
                    backgroundColor:Theme.of(context).colorScheme.onPrimaryContainer,
                    editMode: false,
                    width: 38,
                    activeIconWidth: 22,
                    imageURL: widget.user.image,
                    active: widget.user.activeValue == '1',
                  ),
                ),
                const SizedBox(width: 8), // مسافة أفقية بين العناصر
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(widget.user.fullName, style: theme.textTheme.titleMedium),
                      Text("المستوى: ${widget.user.level}", style: CustomTextStyles.bodySmallOnPrimary),
                    ],
                  ),
                ),
                CustomImageView(
                  imagePath: ImageConstant.imgArrowLeftBlueGray300,
                  height: 32.adaptSize,
                  width: 32.adaptSize,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void showDeleteConfirmation(BuildContext context1, User player) {
    showDialog(
      context: context1,
      builder: (BuildContext context) {
        return DeleteConfirmationDialog(
          playerName: player.fullName,
          titleUser: 'اللاعب',
          onConfirm: () {
            widget.playersTabCubit?.add(DeletePlayerLoadingEvent());
            PlayerController.deleteById(player.playerId??'-1').then((value){
              if(value != null){
                widget.playersTabCubit?.add(DeletePlayerSuccessEvent(userId: player.userId));
                if (kDebugMode) {
                  print('تم حذف اللاعب ${player.fullName}!  ${player.playerId}');
                }
              }else{
                widget.playersTabCubit?.add(DeletePlayerFailedEvent());
              }
            });


          },
        );
      },
    );
  }

  void showAddAttendanceDialog(BuildContext context, User player) {
    if(APISData.cpCubit.state is CPLoading){
      showErrorMessage(message: 'يرجى الانتظار ريثما يتم جلب التمارين والنوادي');
      return;
    }
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AddAttendanceDialog(
          player: player,
        );
      },
    );

  }

  void _showContextMenu(BuildContext context, Offset position) async {
    final RenderBox overlay = Overlay.of(context).context.findRenderObject() as RenderBox;
    final result = await showMenu<int>(
      context: context,
      position: RelativeRect.fromLTRB(
        position.dx,
        position.dy,
        overlay.size.width - position.dx, // المسافة من اليمين
        overlay.size.height - position.dy, // المسافة من الأسفل
      ),
      items: [
        PopupMenuItem(
          height: 32,
          onTap:() {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => PlayerProfileScreen.builder(
                  index: widget.index,
                  context: context,
                  user: widget.user,
                ),
              ),
            );
          },
          child: Row(
            children: [
              Icon(Icons.open_in_new_rounded,color: theme.textTheme.labelLarge?.color,),
              const SizedBox(width: 4,),
              Text('عرض',style: theme.textTheme.labelLarge,),
            ],
          ),
        ),
        PopupMenuItem(
          height: 32,
          onTap:() {
            showDeleteConfirmation(context, widget.user);
          },
          child: Row(
            children: [
              Icon(Icons.delete_outline,color: theme.textTheme.labelLarge?.color,),
              const SizedBox(width: 4,),
              if(widget.playersTabCubit?.selectedMode==true)
                Text("حذف (${widget.playersTabCubit!.selectedUsers.length})",style: theme.textTheme.labelLarge,)
              else
                Text('حذف',style: theme.textTheme.labelLarge,),
            ],
          ),
        ),
        PopupMenuItem(
          height: 32,
          onTap:() {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => AddPlayerPageScreen(
                  player: widget.user,
                  playersTabCubit: widget.playersTabCubit,
                ),
              ),
            );
          },
          child: Row(
            children: [
              Icon(Icons.edit,color: theme.textTheme.labelLarge?.color,),
              const SizedBox(width: 4,),
              Text('تعديل',style: theme.textTheme.labelLarge,),
            ],
          ),
        ),
        PopupMenuItem(
          height: 32,
          onTap: (){
            widget.playersTabCubit?.add(ChangeSelectMode(mod: true));
            setState(() {
              selected = true;
              widget.onSelected?.call(true,widget.user);
            });
          },
          child: Row(
            children: [
              Icon(Icons.check_box_outlined,color: theme.textTheme.labelLarge?.color,),
              const SizedBox(width: 4,),
              Text('تحديد',style: theme.textTheme.labelLarge,),
            ],
          ),
        ),
        PopupMenuItem(
          height: 32,
          onTap: (){
            if(widget.playersTabCubit?.selectedMode == false) {
              widget.playersTabCubit?.add(ChangeSelectMode(mod: true));
            }
            setState(() {
              selected = false;
              widget.onSelected?.call(false,widget.user);
            });
          },
          child: Row(
            children: [
              Icon(Icons.check_box_outline_blank,color: theme.textTheme.labelLarge?.color,),
              const SizedBox(width: 4,),
              Text('إلغاء التحديد',style: theme.textTheme.labelLarge,),
            ],
          ),
        ),
        PopupMenuItem(
          height: 32,
          onTap: (){
            widget.playersTabCubit?.add(ChangeSelectMode(mod: true));
            widget.playersTabCubit?.add(TabSelectAll(value: true));
          },
          child: Row(
            children: [
              Icon(Icons.select_all,color: theme.textTheme.labelLarge?.color,),
              const SizedBox(width: 4,),
              Text('تحديد الكل',style: theme.textTheme.labelLarge,),
            ],
          ),
        ),
        PopupMenuItem(
          height: 32,
          onTap: (){
            widget.playersTabCubit?.add(ChangeSelectMode(mod: false));
            widget.playersTabCubit?.add(TabSelectAll(value: false));
          },
          child: Row(
            children: [
              Icon(Icons.deselect,color: theme.textTheme.labelLarge?.color,),
              const SizedBox(width: 4,),
              Text('إلغاء تحديد الكل',style: theme.textTheme.labelLarge,),
            ],
          ),
        ),
      ],
    );
  }
}